package com.mindpointeye.websockt.javawebsocket

import com.demon.logger.Logger.e
import com.mindpointeye.websockt.DataConvertUtil
import com.mindpointeye.websockt.IWebSocketListener
import org.java_websocket.client.WebSocketClient
import org.java_websocket.drafts.Draft_6455
import org.java_websocket.handshake.ServerHandshake
import java.net.URI
import java.nio.ByteBuffer

class JavaWebSocketClient(
  serverUri: URI?,
  private val listener: IWebSocketListener?
) :
    WebSocketClient(serverUri, Draft_6455()) {

  private val messageDispatcher = MessageDispatcher(listener)

  override fun onOpen(handShakeData: ServerHandshake) {
    e(TAG, "onOpen()")
    listener?.onOpen()
    listener?.onConnectSuccess()
  }

  override fun onMessage(message: String) {
    e(TAG, "onMessage() $message")
    listener?.onMessage(message)

  }

  override fun onClose(
    code: Int,
    reason: String,
    remote: Boolean
  ) {
    e(TAG, "onClose() code $code reason $reason")
    listener?.onClose()
  }

  override fun onError(ex: Exception) {
    e(TAG, "onError()", ex)
    listener?.onConnectFailed()
  }

  override fun onMessage(buffer: ByteBuffer) {
    //To overwrite
    e(TAG, "onMessage() buffer  ${DataConvertUtil.decodeByteBuffer(buffer)}" )
    messageDispatcher.dispatch(buffer)
  }

  inner class MessageDispatcher(private val listener: IWebSocketListener?) {
    fun dispatch(buffer: ByteBuffer) {
//      val requestMessage = TransferMessage.RequestMessage
//          .parseFrom(DataConvertUtil.decodeByteBuffer(buffer))
//      Logger.d(TAG, "onMessage requestMessage  $requestMessage ")
//      if (requestMessage.responseType == TransferMessage.ResponseType.RESP) {
//        dispatchHeartMessage(requestMessage)
//      } else {
//        dispatchOtherMessage(requestMessage)
//      }
    }

//    private fun dispatchHeartMessage(requestMessage: RequestMessage) {
//      Logger.d(TAG, "requestMessage $requestMessage")
//      val builder = ProtoBufManager.createHeartBeat(
//          requestMessage.uid, requestMessage.source
//      )
//      builder?.apply {
//        listener?.onHeartBeatCheck(builder.build().toByteArray())
//      }
//    }
//
//    private fun dispatchOtherMessage(requestMessage: RequestMessage) {
//      listener?.onMessage(requestMessage.responseType.number, requestMessage.source, requestMessage.response)
//    }
  }

  companion object {
    private const val TAG = "JavaWebSocketClient"
  }
}